package com.example.threaddemo.multithread_CyclicBarrier;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class WalkTarget {
    private final CyclicBarrier mBarrier;
    ExecutorService mExecutor;
    //线程方法集合
    private List<Method> mRunThreadMethodList;
    //线程数量
    private Integer mRunThreadMethodSize;

    private Method mBarrierActionMethod;

    private Object mMethodClass;

    private List<Object[]> mParameters;

    private Object[] mBarrierActionMethodParam;

    public class BarrierAction implements Runnable {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            System.out.println("所有线程都已经完成任务,计数达到预设值");
            //mBarrier.reset();//恢复到初始化状态
            try {
                mBarrierActionMethod.invoke(mMethodClass,mBarrierActionMethodParam);
                //mExecutor.shutdown();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }

    public WalkTarget(List<Method> runThreadMethods,Method barrierActionMethod,Object methodClass,List<Object[]> parameters,Object[] barrierActionMethodParam) {

        mRunThreadMethodSize = runThreadMethods.size();
        //初始化CyclicBarrier
        mBarrier = new CyclicBarrier(mRunThreadMethodSize, new BarrierAction());
        mExecutor = Executors.newFixedThreadPool(mRunThreadMethodSize);

        mRunThreadMethodList = runThreadMethods;

        mBarrierActionMethod = barrierActionMethod;

        mMethodClass = methodClass;

        mParameters = parameters;

        mBarrierActionMethodParam = barrierActionMethodParam;

        for (int i = 0; i < mRunThreadMethodSize; i++) {
            //启动工作线程
            mExecutor.execute(new Walker(mBarrier, i , mRunThreadMethodList,mMethodClass,mParameters));
        }
    }
}

